<template>
  <Loading :isLoading="menuStore.loading">
    <div class="flex">
      <Card class="mr-3 w-4">
        <template #title>配置菜单</template>
        <template #content>
          <EditForm v-model:currentMenuItem="currentMenuItem" />
        </template>
      </Card>

      <Card class="flex-1">
        <template #title>菜单列表</template>
        <template #content>
          <TreeTable :value="treeData">
            <Column
              field="name"
              header="名称"
              headerStyle="width: 13rem"
              :expander="true"
            >
              <template #body="slotProps">
                <span class="">
                  <i
                    :class="`pi ${slotProps.node.data.icon} mr-1`"
                    style="font-size: 1rem"
                  ></i>
                  <span>{{ slotProps.node.data.name }}</span>
                </span>
              </template>
            </Column>
            <Column
              field="sort"
              header="排序"
              headerStyle="width: 4rem"
            ></Column>
            <Column field="isUsed" header="是否启用" headerStyle="width: 6rem">
              <template #body="slotProps">
                <InputSwitch
                  v-model="slotProps.node.data.isUsed"
                  @change="handleUsed(slotProps.node)"
                />
              </template>
            </Column>
            <Column
              field="path"
              header="链接地址"
              headerStyle="width: 10rem"
            ></Column>
            <Column header="操作" headerStyle="width: 14rem">
              <template #body="slotProps">
                <div class="flex flex-wrap gap-1">
                  <Button
                    class="w-2rem h-2rem"
                    v-tooltip.top="'新增菜单'"
                    icon="pi pi-plus"
                    severity="info"
                    aria-label="User"
                    @click="handleOperate('add', slotProps.node)"
                  />
                  <Button
                    class="w-2rem h-2rem"
                    v-tooltip.top="'更新菜单'"
                    icon="pi pi-pencil"
                    severity="warning"
                    aria-label="Notification"
                    @click="handleOperate('update', slotProps.node)"
                  />
                  <Button
                    class="w-2rem h-2rem"
                    v-tooltip.top="'菜单授权'"
                    icon="pi pi-sliders-h"
                    severity="help"
                    aria-label="Favorite"
                    @click="handleOperate('', slotProps.node)"
                  />
                  <Button
                    class="w-2rem h-2rem"
                    v-tooltip.top="'删除菜单'"
                    icon="pi pi-times"
                    severity="danger"
                    aria-label="Cancel"
                    @click="handleOperate('delete', slotProps.node)"
                  />
                </div>
              </template>
            </Column>
          </TreeTable>
        </template>
      </Card>
    </div>
  </Loading>
  <ConfirmDialog class="w-3" />
</template>

<script setup lang="ts">
import { useMenuStore } from "@/stores/menu";
import { onMounted, ref } from "vue";
import { useToast } from "vue-toastification";
import { useRouter } from "vue-router";
import {
  Card,
  TreeTable,
  Button,
  Column,
  InputSwitch,
  useConfirm,
  ConfirmDialog,
} from "@/utils/primevue";
import Loading from "@/components/Loading/Loading-component";
import EditForm from "./components/EditForm.vue";
import type { TreeNode } from "primevue/tree";
import type { TAllMenuInfo } from "@/typing/base";

const menuStore = useMenuStore();
const treeData = ref();
const toast = useToast();
const confirm = useConfirm();
const router = useRouter();

const currentMenuItem = ref<Partial<TAllMenuInfo>>({
  icon: "",
  id: 0,
  path: "",
  name: "",
  pid: 0,
});

onMounted(() => {
  menuStore.queryMenuList();
});

menuStore.$subscribe(() => {
  treeData.value = menuStore.getNodes.nodes;
});

const handleUsed = (data: TreeNode) => {
  menuStore.updateMenuUsed(
    {
      id: data.key as string,
      used: data.data.isUsed ? 1 : -1,
    },
    () => {
      toast.success("更新启用状态成功！");
    }
  );
};

const deleteMenu = (id: number) => {
  confirm.require({
    message: "你想要删除这个菜单吗?",
    header: "删除确认",
    icon: "pi pi-info-circle",
    acceptClass: "p-button-danger",
    accept: () => {
      menuStore.deleteMenu(id, () => {
        toast.success("删除菜单成功！");
        menuStore.queryMenuList({ force: true });
      });
    },
    reject: () => {},
  });
};

const goMenuAction = (node: TreeNode) => {
  if (node.level === 1) {
    confirm.require({
      message: "当前菜单无需配置功能权限",
      header: "温馨提示",
      icon: "pi pi-exclamation-triangle",
      accept: () => {},
      reject: () => {},
    });
  } else {
    router.push({
      path: "/admin/menu-action/" + node.id,
      query: {
        name: node.name
      }
    });
  }
};

const handleOperate = (oper: string, data: TreeNode) => {
  const current = menuStore.filterMenu(parseInt(data.key as string));
  if (oper === "add") {
    currentMenuItem.value = { pid: current.id, level: current.level + 1 };
  } else if (oper === "update") {
    // 当前需要修改的item，如果 pid 不存在，表示是一级菜单，设置为 0
    currentMenuItem.value = { pid: 0, ...current };
  } else if (oper === "delete") {
    deleteMenu(current.id);
  } else {
    goMenuAction(current);
  }
};
</script>

<style lang="less" scoped></style>
